﻿using AutoMapper;
using Server.Dto;
using Server.Entity;
using System;
using System.Collections.Generic;

namespace Server.Core.Service
{
    public class BusinessService
    {
        static BusinessService()
        {
            Mapper.Initialize(t =>
            {
                t.CreateMap<Product, ProductDto>();
                t.CreateMap<ProductDto, Product>();

                t.CreateMap<Channel, ChannelDto>();
                t.CreateMap<ChannelDto, Channel>();
            });
        }

        public List<ProductDto> GetProducts(string name)
        {
            return DbContext.Execute(d =>
            {
                return d.Queryable<Product>()
                    .WhereIF(!string.IsNullOrWhiteSpace(name), it => it.Name.Contains(name))
                    .Select<ProductDto>()
                    .Mapper(p => { p.Channels = GetProductChannels(p); })
                    .ToList();
            });
        }

        public List<ChannelDto> GetProductChannels(ProductDto p)
        {
            return DbContext.Execute(t => t.Queryable<Channel>()
                .Where(ct => ct.ProductId == p.Id)
                .Select<ChannelDto>()
                .Mapper(ct => ct.Product = p)
                .ToList());
        }

        public void SaveProduct(ProductDto product)
        {
            DbContext.Execute(t =>
            {
                var p = Mapper.Map<Product>(product);
                if (p.Id == Guid.Empty)
                {
                    p.Id = Guid.NewGuid();
                    t.Insertable(p).ExecuteCommand();
                }
                else
                {
                    t.Updateable(p).ExecuteCommand();
                }
            });
        }

        public void DeleteProduct(ProductDto product)
        {
            var p = Mapper.Map<Product>(product);
            DbContext.Execute(t => t.Deleteable(p).ExecuteCommand());
        }
    }
}
